#include "TextureWidget.h"

#include <QPainter>
#include <QPaintEvent>

#include "Project.h"

QRect TextureWidget::visualRect( const QModelIndex & modelIndex ) const
{
    if( model() )
    {
        return model()->data( modelIndex.sibling( modelIndex.row(), Project::TextureRectColumn ), Project::RectRole ).toRect().adjusted( -2, -2, 2, 2 );
    }

    return QRect();
}

QModelIndex TextureWidget::indexAt( const QPoint &/*point*/ ) const
{
    //:TODO:

    return QModelIndex();
}

void TextureWidget::paintEvent( QPaintEvent * event )
{
    QPainter
        painter( viewport() );

    painter.fillRect( event->rect(), Qt::gray );
    painter.drawPixmap( QPoint( 0, 0 ), CacheTexture );

    painter.setPen( Qt::red );

    foreach( QModelIndex index, selectedIndexes() )
    {
        painter.drawRect( index.sibling( index.row(), Project::TextureRectColumn ).data( Project::RectRole ).toRect() );
    }
}

void TextureWidget::updateGeometries()
{
    CacheTexture = QPixmap( 512, 1024 );
    CacheTexture.fill( Qt::transparent );
    
    if( model() )
    {
        QPainter painter( &CacheTexture );

        painter.setPen( Qt::white );

        for( int i = 0; i < model()->rowCount(); ++i )
        {
            painter.drawPixmap(
                model()->index( i, Project::TextureRectColumn ).data( Project::RectRole ).toRect(),
                model()->index( i, Project::GlyphColumn ).data( Project::PixmapRole ).value<QPixmap>()
                );
        }
    }
}